let BaseController = require('./BaseController')
let fs = require('fs')
let path = require('path')
let cheerio = require('cheerio')

class Controller extends BaseController {
    constructor() {
        super();
        this.baseSrc = `d:/数据指标分类/${new Date().format('yyyyMMdd')}/待入库/06日龙虎榜/每日龙虎榜明细/`
        this.companyCodeArr = [];
        this.companyCodeIndex = 0;
        this.encode = 'GBK'
        this.paramsArr = []
        this.paramsIndex = 0;
    }
    /**
     * 获取url
     * @param date 证券公司code
     */
    getUrl(date) {
        return `http://data.eastmoney.com/stock/lhb,${this.params['date']},${this.params['sharesCode']}.html`
    }
    /**
     * 获取参数
     * 读取每日龙虎榜csv，拿到日期 股票代码
     */
    getParams() {
        let paramsFileSrc = `d:/数据指标分类/${new Date().format('yyyyMMdd')}/待入库/06日龙虎榜/每日龙虎榜/`
        let paramsArr = [];
        let files = fs.readdirSync(paramsFileSrc);
        files.map(fileName => {
            let date = fileName.match(/(\d+)?\.csv/)[1] || ''
            let fileContent = fs.readFileSync(paramsFileSrc + fileName).toString()
            if (date && fileContent && fileContent.split(/\n/).length) {
                date = new Date(`${date.substr(0, 4)}-${date.substr(4, 2)}-${date.substr(6, 4)}`).format('yyyy-MM-dd');
                fileContent.split(/\n/).map((row, i) => {
                    let sharesCode = row.split(',')[0]
                    if (i > 0 && sharesCode) {
                        paramsArr.push({ date, sharesCode })
                    }
                })
            }
        })
        this.paramsArr = paramsArr
    }

    /**
     * 获取历史数据
     */
    async getHistory() {
        console.log('7每日龙虎榜明细Controller')
        if (this.paramsIndex < this.paramsArr.length) {
            try {
                this.params = this.paramsArr[this.paramsIndex]
                console.log(this.paramsIndex)
                console.log(this.params)
                let data = await this.getData(null, this.isCache)
                this.writeCsv(data)
                this.paramsIndex++;
            } catch (err) {
                console.log(err)
            }
            await this.getHistory();
        }
    }
    /**
     * 数据格式化
     */
    axiosDataFormat(data) {
        let result = null
        try {
            result = JSON.parse(data.replace(/^var\s\w+?\s*\=/, '').trim())
        } catch (err) {
            try {
                result = eval('(' + data.replace(/^var\s\w+?\s*\=/, '').trim() + ')')
            } catch (err) {
                if (data.indexOf('502 Bad Gateway') > -1) {
                    return []
                } else {
                    console.log(err)
                }

            }
        }
        return result
    }

    /**
     * 写csv
     */
    writeCsv(arr) {
        if (!fs.existsSync(this.baseSrc)) {
            this.mkdirs(this.baseSrc)
        }
        this.file = `每日龙虎榜明细_${this.params['sharesCode']}_${new Date(this.params['date']).format('yyyyMMdd')}.csv`
        fs.writeFileSync(path.join(this.baseSrc, this.file), this.convertToCSV(arr, 'title'), 'UTF-8')
    }

    /**
     * 从网页源码提取数据，并且格式化成arr
     */
    outputDataFormat(data) {
        let self = this;
        let sharesCode = self.params['sharesCode']
        let $ = cheerio.load(data.toString(), { decodeEntities: true });
        let arr = []
        $('.content-sepe').map((index, content) => {
            try {
                let 买卖类型 = $(content).find('#tab-2 thead .th-title').text().trim();
                let 类型 = $(content).prev().find('.left.con-br').text().split('类型：')[1].trim()
                let 股票ID = self.params.sharesCode;
                $(content).find('#tab-2 tbody tr').map(function (i, tr) {
                    let 营业部ID = $(tr).find('.sc-name a').last().attr('href').match(/(\d+)\.html/) ? $(tr).find('.sc-name a').last().attr('href').match(/(\d+)\.html/)[1] : '-1'
                    let 营业部名称 = $(tr).find('.sc-name a').last().text().trim()
                    let 买入金额 = $(tr).find('td').eq(2).text();
                    let 买入金额占总成交比例 = $(tr).find('td').eq(3).text();
                    let 卖出金额 = $(tr).find('td').eq(4).text();
                    let 卖出金额占总成交比例 = $(tr).find('td').eq(5).text();
                    let 净额 = $(tr).find('td').eq(6).text();
                    let 上榜次数 = $(tr).find('.times-percent .times').text().trim();
                    let 上涨率 = $(tr).find('.times-percent .percent').text().trim();
                    let obj = { index, 股票ID, 营业部ID, 营业部名称, 上榜次数, 上涨率, 买入金额, 买入金额占总成交比例, 卖出金额, 卖出金额占总成交比例, 净额, 类型, 买卖类型 }
                    arr.push(obj)
                })
                买卖类型 = $(content).find('#tab-4 thead .th-title').text()
                $(content).find('#tab-4 tbody tr').map(function (i, tr) {
                    if ($(tr).text().indexOf('总合计:') == -1) {
                        let 营业部ID = $(tr).find('.sc-name a').last().attr('href').match(/(\d+)\.html/) ? $(tr).find('.sc-name a').last().attr('href').match(/(\d+)\.html/)[1] : '-1';
                        let 营业部名称 = $(tr).find('.sc-name a').last().text().trim()
                        let 买入金额 = $(tr).find('td').eq(2).text();
                        let 买入金额占总成交比例 = $(tr).find('td').eq(3).text();
                        let 卖出金额 = $(tr).find('td').eq(4).text();
                        let 卖出金额占总成交比例 = $(tr).find('td').eq(5).text();
                        let 净额 = $(tr).find('td').eq(6).text();
                        let 上榜次数 = $(tr).find('.times-percent .times').text().trim();
                        let 上涨率 = $(tr).find('.times-percent .percent').text().trim();
                        let obj = { index, sharesCode, 营业部ID, 营业部名称, 上榜次数, 上涨率, 买入金额, 买入金额占总成交比例, 卖出金额, 卖出金额占总成交比例, 净额, 类型, 买卖类型 }
                        arr.push(obj)
                    }
                })
            } catch (err) {
                self
                console.log(err)
            }
        })

        return arr
    }

    async main(startDate = '2015-01-01', isCache = true) {
        this.isCache = isCache;
        console.log('--->7每日龙虎榜明细Controller')
        this.getParams()
        await this.getHistory()
    }
}

let controller = new Controller()
module.exports = controller
